/*
 * @path        : \threejs\config\pages.config.js
 * @Author      : yvangod
 * @since       : 2021-03-10 13:53:03
 * @LastAuthor  : yvangod
 * @lastTime    : 2021-04-02 17:25:18
 * @message     : 走好每一步，才能走的更快更稳
 */
const fs = require("fs")
const paths = require('./paths')
const path = require('path')
const glob = require('glob')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const getEntries = (dirUrl) => {
  let entries = {};
  let entriesDetails = [];
  const dirUrlArr = glob.sync(dirUrl);
  dirUrlArr.map((jsPath, index) => {
    let entry_name = "";
    let _jsPath = jsPath.slice(0, jsPath.lastIndexOf("/"));
    entry_name = _jsPath.slice(_jsPath.lastIndexOf("/") + 1);
    entries[entry_name] = [jsPath];
    entriesDetails[index] = {
      name: entry_name,
      filePath: jsPath,
      dir: _jsPath,
    }
  })
  return {
    entries,
    entriesDetails,
  };
}

const getHTMLPluginConfig = (dirUrl) => {
  let temps = getEntries(dirUrl).entriesDetails;

  let conf = {
    inject: true,
    favicon: paths.public + '/favicon.png',
  }
  return temps.map(({ name, filePath, dir }) => {
    return new HtmlWebpackPlugin(Object.assign({}, conf, {
      template: filePath,
      filename: `${name}.html`,
      chunks: ['manifest', 'vendor', `${name}`]
    }));
  })
}

const getAllPage = (dirUrl) => {
  let temps = getEntries(dirUrl).entriesDetails
  return temps.map(({ name, filePath, dir }) => {
    const tempHtmlStr = fs.readFileSync(filePath, "utf-8")
    let _start_idx = tempHtmlStr.indexOf("<title>") + 7
    let _end_idx = tempHtmlStr.indexOf("</title>")
    let title = tempHtmlStr.slice(_start_idx, _end_idx)
    return {
      name,
      filePath,
      dir,
      title
    }
  })
}

fs.writeFile("./src/common/menu.json", JSON.stringify(getAllPage(paths.src + "/pages/**/*.html")), {
  encoding: "utf8"
}, (err) => {
  if(err){
    console.log(err)
  }
});

module.exports = {
  entries: getEntries(paths.src + "/pages/**/*.js").entries,
  HTMLPluginConfig: getHTMLPluginConfig(paths.src + "/pages/**/*.html")
};
